package com.largeOrange.controller;

import com.largeOrange.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class UploadAndDownLoadController {
    @Value("${load}")
    private String imgLoad;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        //截取图片文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info(suffix);
        //随机生成文件名防止出现相同文件名出现文件覆盖
        String fileName = UUID.randomUUID().toString()+suffix;
        log.info(fileName);
        //图片存放路径,如果文件不存在，则新建文件
        File imgFile = new File(imgLoad);
        if (!imgFile.exists()) {
            imgFile.mkdir();
        }
        //开始下载
        try {
            file.transferTo(new File(imgLoad+"\\"+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info(imgLoad);
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //log.info(name);
        try {
            FileInputStream inputStream = new FileInputStream(imgLoad + "\\" + name);
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int count=0,index=0;
            byte[] bytes = new byte[1024];
            while ((count=inputStream.read(bytes))!=-1){
                log.info("-------------------》》》》第"+(++index)+"次读取了"+count+"个字节！");
                outputStream.write(bytes,0,count);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
